package com.tinama.jedis01.lock8;

import java.util.Date;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lgc
 * @createDate 2020/11/10 - 16:52
 */
public class ConditionTest {
    public static void main(String[] args){
        Datas datas = new Datas();
        new Thread(()->{
              for (int i = 0; i < 3; i++) {
                  datas.printfA();
              }
          },"线程A").start();
        new Thread(()->{
            for (int i = 0; i < 3; i++) {
                datas.printfB();
            }
        },"线程B").start();
        new Thread(()->{
            for (int i = 0; i < 3; i++) {
                datas.printfC();
            }
        },"线程C").start();
    }
}
class Datas{
    private int i = 0;
    private Lock lock= new ReentrantLock();
    private Condition condition0 = lock.newCondition();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();

    public void printfA(){
        lock.lock();
        try {
            while (i!=0){
                condition0.await();
            }
            i=1;
            System.out.println(Thread.currentThread().getName()+"打印A0");
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printfB(){
        lock.lock();
        try {
            while (i!=1){
                condition1.await();
            }
            i=2;
            System.out.println(Thread.currentThread().getName()+"打印B1");
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printfC(){
        lock.lock();
        try {
            while (i!=2){
                condition2.await();
            }
            i=0;
            System.out.println(Thread.currentThread().getName()+"打印C2");
            condition0.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}

